package com.dianban.controller.shaliangjie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.User;
import com.dianban.service.FacePayStoreOrderService;
import com.dianban.service.UserService;
import com.dianban.utils.DateUtils;
import com.dianban.utils.XiaomaiguiUtils;
import com.dianban.utils.http.AjaxResult;
import com.dianban.weixin.util.WechatUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.*;

@RestController
@Api(value = "ApiSljXiaomaiguiController", description = "沙粮姐自助售卖柜控制器")
@RequestMapping(value = "${interfacePath}/shaliangjie/xiaomaigui/")
public class ApiSljXiaomaiguiController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiSljXiaomaiguiController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;

    @RequestMapping("/notify")
    @ResponseBody
    public AjaxResult notify(@RequestBody String jsonStr, HttpServletRequest request, HttpServletResponse response) {
        //logger.info("沙粮姐自助售卖柜回调");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //logger.info("jsonStr-{}", URLDecoder.decode(jsonStr, "utf-8"));
            JSONObject json = JSONObject.parseObject(URLDecoder.decode(jsonStr, "utf-8"));
            String appid = String.valueOf(json.get("appid"));
            String data = String.valueOf(json.get("data"));
            //logger.info("appid-{}", appid);
            if (XiaomaiguiUtils.APPID.equalsIgnoreCase(appid)) {
                //logger.info("data-{}", data);
                if (StringUtils.isNotBlank(data)) {
                    JSONObject jsonObject = JSONObject.parseObject(data);
                    if (jsonObject != null) {
                        String event_type = String.valueOf(jsonObject.get("event_type"));
                        //logger.info("event_type-{}", event_type);
                        // 机柜注册
                        if (StringUtils.isNotBlank(event_type) && "bindRack".equalsIgnoreCase(event_type)) {
                            // 注册
                            resultMap.put("devid", jsonObject.get("boxdevid"));
                            resultMap.put("machinesn", jsonObject.get("containerid"));
                            resultMap.put("doosposturl", "");
                            return new AjaxResult(10000, "绑定成功", resultMap);
                        }
                        // 机柜激活
                        if (StringUtils.isNotBlank(event_type) && "registerRack".equalsIgnoreCase(event_type)) {
                            List<Map<String, Object>> resultList = new ArrayList<>();
                            JSONObject paramsObject = JSONObject.parseObject(String.valueOf(jsonObject.get("params")));
                            // 激活
                            resultMap.put("code", "10000");
                            resultMap.put("machinesn", paramsObject.get("containerid"));
                            resultMap.put("msg", "success");
                            resultList.add(resultMap);
                            return new AjaxResult(10000, "机柜激活成功", resultList);
                        }
                        // 订单推送
                        if (StringUtils.isNotBlank(event_type) && "order".equalsIgnoreCase(event_type)) {
                            //转换data数据
                            String orderNo = jsonObject.getString("orderNo");
                            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(orderNo);
                            if (facePayStoreOrder == null) {
                                return new AjaxResult(400, "订单编号错误", "");
                            }
                            JSONArray orderinfoArray = JSON.parseArray(jsonObject.getString("orderinfo"));
                            BigDecimal money = BigDecimal.ZERO;
                            String goodinfo = "";
                            for (int i = 0; i < orderinfoArray.size(); i++) {
                                JSONObject orderinfo = orderinfoArray.getJSONObject(i);
                                // totalfee 是 string总售价 单位分
                                // goodsname 是 string商品名称
                                String totalfeeStr = orderinfo.getString("totalfee");
                                BigDecimal totalfee = new BigDecimal(totalfeeStr).divide(new BigDecimal(100), 2, RoundingMode.UP);
                                money = money.add(totalfee);
                                String goodsname = orderinfo.getString("goodsname");
                                if (StringUtils.isNotBlank(goodsname)) {
                                    if (StringUtils.isBlank(goodinfo)) {
                                        goodinfo = goodsname;
                                    } else {
                                        goodinfo = goodinfo + "、" + goodsname;
                                    }
                                }
                            }
                            // 有订单并且金额大于0
                            if (!CollectionUtils.isEmpty(orderinfoArray) && money.compareTo(BigDecimal.ZERO) > 0) {
                                facePayStoreOrder = new FacePayStoreOrder();
                                facePayStoreOrder.setOrderNumber(orderNo);
                                facePayStoreOrder.setMoney(money);
                                facePayStoreOrder.setPayStatus(10);
                                facePayStoreOrder.setCommissionStatus(10);
                                facePayStoreOrder.setOrderinfo(data);
                                facePayStoreOrder.setGoodinfo(goodinfo);
                                facePayStoreOrderService.updateSlj(facePayStoreOrder);
                                // 推送一条待支付消息
                                try {
                                    FacePayStoreOrder order = facePayStoreOrderService.findByOrderNumber(orderNo);
                                    if (order != null) {
                                        User user = userService.findById(order.getUserId());
                                        if (user != null && StringUtils.isNotBlank(user.getOpenid())) {
                                            WechatUtils.wait_pay(user.getOpenid(), orderNo, DateUtils.format(new Date(order.getCreatetime() * 1000), DateUtils.Y_M_D_H_M_S), String.valueOf(money), "有订单等待支付，如您已支付，请忽略本消息！");
                                        }
                                    }
                                } catch (Throwable e) {
                                    e.printStackTrace();
                                }
                            } else {
                                // 空订单以及金额小于0
                                facePayStoreOrder = new FacePayStoreOrder();
                                facePayStoreOrder.setOrderinfo(data);
                                facePayStoreOrder.setGoodinfo(goodinfo);
                                facePayStoreOrderService.updateSlj(facePayStoreOrder);
                            }
                            return new AjaxResult(200, "success", "");
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("沙粮姐自助售卖柜回调接口异常," + e.toString());
            return new AjaxResult(10002, "系统异常，请稍后重试或联系管理员！", resultMap);
        }
        return new AjaxResult(10000, "获取成功", resultMap);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String jsonStr = "%7B%22appid%22%3A%227009013ce4f4fe6dee54211571cc3198%22%2C%22sign%22%3A%22Girlo9De7N6sapriLSV5pI1YnaNtOTFn+gd1CXrDp7CmgyT7m5Umg8+tzlkKc8I3fSNxzsqG+bHIj19jS15SF0TyIV%5C%2FGpyn39Ce%5C%2FG1wP5uGHEEmprm1bS6kdf0sT78xwSPy%5C%2FmBZH1RC0Naztv8t3gwMZplFqdRchB9xbWbswYpzRt7SK8+361Vec4ovP9OikfkM%5C%2FSc8d9LdPOnkJd%5C%2FzvtRFm6iASPi4+r18HPBTbq4IUfZCfKd8nGyCxFEF0yK46bI3zTEU5YZnaOsSHTTNtdshIIUru8PQCTxAM59njjXasYuZZI4DqoCYGfFdF2sHSXCxoLdQ2NwqgaaXDlMTckg=%3D%22%2C%22data%22%3A%7B%22containerid%22%3A%22869012040985959%22%2C%22boxdevid%22%3A%22869012040985959%22%2C%22event_type%22%3A%22bindRack%22%7D%7D";
        System.out.println(URLDecoder.decode(jsonStr, "utf-8"));
    }
}
